package com.gzhryc.shared_device.oem.h5.mng.controllers.agent;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.DefaultEnum;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.models.PortableEnergyBatteryPlaceCount;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryService;
import com.gzhryc.shared_device.common.device.dao.models.PlaceDeviceCount;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentFuncModel;
import com.gzhryc.shared_device.oem.code.agent.services.AgentBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentFuncModelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentLevelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentSearch;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.config.BusinessConfig;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.models.PlaceUserCount;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

public class AgentController {

    @Route(value = { "/agent/list.html" })
    public String list(HttpServletRequest request) {
        return "/agent/list.html";
    }

    @Route(value = "/agent/list.data")
    public ListResult<Agent> listData(HttpServletRequest request) {
        ListResult<Agent> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        AgentSearch search = WebUtils.getParameter(request, AgentSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(AgentService.self().countJoinBySearch(search));
        result.getBody().setData(AgentService.self().findJoinBySearch(search, pageNo, pageLimit));

        if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
            result.setCode(DtoConstants.SUCCESS,null);
        }
        return result;
    }

    @Route(value = { "/agent/add.html" })
    public String add(HttpServletRequest request) {
        BusinessConfig config = ConfigUtils.getBusinessConfig();
        request.setAttribute("serviceChargeRatio",config.getServiceChargeRatio());
        request.setAttribute("sexList", DefaultEnum.Sex.values());
        request.setAttribute("levelList", AgentLevelService.self().findAll());
        return "/agent/edit.html";
    }

    @Route(value = { "/agent/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        Agent agent = WebUtils.getParameter(request, Agent.class);
        User user = WebUtils.getParameter(request,User.class);
        try {
            if(AgentService.self().add(agent,user)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/info.html" })
    public String info(HttpServletRequest request) {
        Long userId = WebUtils.getLong(request,"userId");
        Agent agent = AgentService.self().getJoinByUserId(userId);
        WebUtils.setAttribute(request,agent);
        request.setAttribute("sexList", DefaultEnum.Sex.values());
        request.setAttribute("levelList", AgentLevelService.self().findAll());
        return "/agent/info.html";
    }
  
    @Route(value = "/agent/busi_config/list.data")
    public ListResult<AgentBusinessConfig> busiConfigListData(HttpServletRequest request) {
        ListResult<AgentBusinessConfig> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request, "userId");
        if(userId != null) {
        	List<AgentBusinessConfig> data = AgentBusinessConfigService.self().findByUserId(userId);
        	if(data != null && data.size() > 0) {
        		result.setCode(DtoConstants.SUCCESS, null);
        		result.getBody().setData(data);
        	}
        }
        return result;
    }
  
    @Route(value = { "/agent/busi_config/add.html" })
    public String addBusiConfig(HttpServletRequest request) {
    	List<EBusinessType> businessTypeList = new ArrayList<EBusinessType>();
    	businessTypeList.add(EBusinessType.BXSCN);
    	businessTypeList.add(EBusinessType.BXSCN_SHOP);
    	businessTypeList.add(EBusinessType.CDB);
    	businessTypeList.add(EBusinessType.CDCZ);
    	businessTypeList.add(EBusinessType.PCL);
    	request.setAttribute("businessTypeList", businessTypeList);
        return "/agent/busi_config/edit.html";
    }
    
    @Route(value = { "/agent/busi_config/add.do" })
    public AjaxResult doAddBusiConfig(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败，请稍后再试");
        AgentBusinessConfig businessConfig = WebUtils.getParameter(request, AgentBusinessConfig.class);
        try {
            if(AgentBusinessConfigService.self().add(businessConfig)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
    
    @Route(value = { "/agent/busi_config/update.html" })
    public String updateBusiConfig(HttpServletRequest request) {
    	Long userId = WebUtils.getLong(request, "userId");
    	String businessType = WebUtils.getString(request, "businessType");
    	AgentBusinessConfig businessConfig = AgentBusinessConfigService.self().getByKeys(userId, businessType);
    	WebUtils.setAttribute(request, businessConfig);
        return "/agent/busi_config/edit.html";
    }
    
    @Route(value = { "/agent/busi_config/update.do" })
    public AjaxResult doUpdateBusiConfig(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败，请稍后再试");
        AgentBusinessConfig businessConfig = WebUtils.getParameter(request, AgentBusinessConfig.class);
        try {
            if(AgentBusinessConfigService.self().updateNotNull(businessConfig)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/busi_config/del.do" })
    public AjaxResult doDelBusiConfig(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        String businessType = WebUtils.getString(request, "businessType");
        try {
            if(AgentBusinessConfigService.self().deleteByKeys(userId,businessType)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/service_charge_ratio/update.html" })
    public String updateServiceChargeRatio(HttpServletRequest request) {
        Long userId = WebUtils.getLong(request,"userId");
        Agent agent = AgentService.self().getByUserId(userId);
        WebUtils.setAttribute(request,agent);
        return "/agent/edit_service_charge_ratio.html";
    }

    @Route(value = { "/agent/service_charge_ratio/update.do" })
    public AjaxResult doUpdateServiceChargeRatio(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        Double serviceChargeRatio = WebUtils.getDouble(request,"serviceChargeRatio");
        try {
            if(AgentService.self().updateServiceChargeRatio(userId,serviceChargeRatio)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    
    @Route(value = { "/agent/cfg_level/update.html" })
    public String updateLevel(HttpServletRequest request) {
        Long userId = WebUtils.getLong(request,"userId");
        Agent agent = AgentService.self().getByUserId(userId);
        WebUtils.setAttribute(request,agent);
        request.setAttribute("levelList", AgentLevelService.self().findAll());
        return "/agent/edit_level.html";
    }

    @Route(value = { "/agent/cfg_level/update.do" })
    public AjaxResult doUpdateLevel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"修改失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        Integer level = WebUtils.getInteger(request,"level");
        try {
            if(AgentService.self().updateLevel(userId,level)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        try {
            if(AgentService.self().deleteById(userId)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
    
    @Route(value = { "/agent/place/list.html" })
    public String placeList(HttpServletRequest request) {
    	 Long userId = WebUtils.getLong(request,"userId");
    	 Agent agent = AgentService.self().getJoinByUserId(userId);
         WebUtils.setAttribute(request,agent);
        return "/agent/place/list.html";
    }

    @Route(value = "/agent/place/list.data")
    public ListResult<PlacePhysicalStore> placeListData(HttpServletRequest request){
        ListResult<PlacePhysicalStore> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        if(userId != null) {
            PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
            search.setUserId(userId);

            result.getBody().setTotal(PlacePhysicalStoreService.self().countJoinBySearch(search));
            List<PlacePhysicalStore> data = PlacePhysicalStoreService.self().findJoinBySearch(search, pageNo, pageLimit);
            if (data != null && data.size() > 0) {
            	List<Long> placeIds = new ArrayList<>();
            	for(PlacePhysicalStore place:data) {
            		place.setUserCount(1L);	//1代表代理自己
            		place.setDeviceCount(0L);
            		placeIds.add(place.getId());
            	}
            	
            	List<PlaceUserCount> userCountList = PlaceProfitUserService.self().findUserCountByPlaceId(placeIds);
            	if(userCountList != null && userCountList.size() > 0) {
            		for(PlacePhysicalStore place:data) {
            			for(PlaceUserCount item : userCountList) {
            				if(item.getPlaceId().equals(place.getId())) {
            					place.setUserCount(item.getUserCount() + 1);
            					break;
            				}
            			}
                	}
            	}
            	
            	List<PlaceDeviceCount> deviceCountList = DeviceService.self().countPlaceByPlaceIds(placeIds);
            	if(deviceCountList != null && deviceCountList.size() > 0) {
            		for(PlacePhysicalStore place:data) {
            			for(PlaceDeviceCount item : deviceCountList) {
            				if(item.getPlaceId().equals(place.getId())) {
            					place.setDeviceCount(item.getDeviceCount());
            					break;
            				}
            			}
                	}
            	}
            	
            	if(BaseConstants.getBXSCN()) {
                	List<PortableEnergyBatteryPlaceCount> batteryCountList = PortableEnergyBatteryService.self().findPlaceCountByPlaceIds(placeIds);
                	if(batteryCountList != null && batteryCountList.size() > 0) {
                		for(PlacePhysicalStore place:data) {
                			for(PortableEnergyBatteryPlaceCount item : batteryCountList) {
                				if(item.getPlaceId().equals(place.getId())) {
                					place.setDeviceCount(place.getDeviceCount() + item.getDeviceCount());
                					break;
                				}
                			}
                    	}
                	}
                }
            	
                result.setCode(DtoConstants.SUCCESS, null);
                result.getBody().setData(data);
            }
        }
        return result;
    }

    @Route(value = "/agent/func_model/list.data")
    public ListResult<AgentFuncModel> funcModelListData(HttpServletRequest request) {
        ListResult<AgentFuncModel> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        result.getBody().setData(AgentFuncModelService.self().findJoinByUserId(userId));
        if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
        	String resDomain = WebConstants.getResDomain(request);
            for(AgentFuncModel item : result.getBody().getData()){
                if(StringTools.isNotBlank(item.getFuncModel().getIconUrl())){
                    item.getFuncModel().setIconUrl(resDomain + item.getFuncModel().getIconUrl());
                }
            }
            result.setCode(DtoConstants.SUCCESS, null);
        }
        return result;
    }

    @Route(value = { "/agent/func_model/add.html" })
    public String addFuncModel(HttpServletRequest request) {
        return "/agent/edit_func_model.html";
    }

    @Route(value = { "/agent/func_model/add.do" })
    public AjaxResult doAddFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"新增失败，请稍后再试");
        AgentFuncModel userFuncModel = WebUtils.getParameter(request, AgentFuncModel.class);
        try {
            if(AgentFuncModelService.self().add(userFuncModel)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/agent/func_model/del.do" })
    public AjaxResult doDelFuncModel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        Long funcModelId = WebUtils.getLong(request,"funcModelId");
        try {
            if(AgentFuncModelService.self().deleteByKeys(userId,funcModelId)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/agent/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);

        AgentSearch search = new AgentSearch();
        search.setTrim(term);
        Long total = 0L;
        List<Agent> list = AgentService.self().findJoinBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            for (Agent agent : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(agent.getUserId().toString());
                item.setText(agent.getUser().getName() + "("+agent.getUser().getPhone()+")");
                result.getBody().getData().add(item);
            }
            total += list.size();
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }
}
